import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hitutor/UI/Home/Home.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../WebPage.dart';

class Register extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _Register();
  }
}

class _Register extends State {
  bool agree = false;
  List<dynamic> countrieCodeList = [];
  String phoneCode = "886";
  List<dynamic> lessonList = [];
  dynamic lesson;

  TextEditingController emailController = TextEditingController();
  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getPhoneCode();
      getLesson();
    });
    super.initState();
  }

  getLesson() {
    HttpGo(context).get("/Lesson/GetTestCourseList", {}, (data) {
      lessonList = data["courses"];
    }, (code, error) => showToast(error));
  }

  chooseLesson() {
    showWheelDialog2(context, "", lessonList, "courseName", (index) {
      lesson = lessonList[index];
      setState(() {});
    });
  }

  getPhoneCode() {
    HttpGo(context).get("/Login/GetCountryCodeList", {}, (data) {
      countrieCodeList = data["countrieCodeList"];
    }, (code, error) => showToast(error), showLoading: false);
  }

  choosePhoneCode() {
    showWheelDialog(context, "", countrieCodeList, (index) {
      phoneCode = countrieCodeList[index];
      setState(() {});
    });
  }

  register() {
    String email = emailController.text;
    String name = nameController.text;
    String phone = phoneController.text;
    if (email.isEmpty || name.isEmpty || phone.isEmpty) {
      showToast("請將資料填寫完整");
      return;
    }
    if (lesson == null) {
      showToast("請選擇試讀課程");
      return;
    }
    if (!agree) {
      showToast("請同意隱私權政策");
      return;
    }
    HttpGo(context).post("/Member/Register", {
      "email": email,
      "studentName": name,
      "countryCode": phoneCode,
      "mobilePhone": phone,
      "classCode": lesson["courseId"],
      "className": lesson["courseName"],
      "privacyPolicy": agree
    }, (data) {
      Global.regTip = data["message"];
      Global.saveUserInfo(data["token"], data["studentId"], data["userId"], name, () {
        PageUtil().openRemoveAll(context, Home(register: true));
      });
    }, (code, error) => showToast(error));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            color: MyColor.F8,
            alignment: Alignment.center,
            padding: EdgeInsets.fromLTRB(22, 0, 22, 0),
            child: SingleChildScrollView(
                child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [
              LocalImage("sign-up.png", width: 120),
              Container(
                  width: double.infinity,
                  decoration: Global.getWhiteBg(8),
                  padding: EdgeInsets.all(22),
                  child: Column(children: [
                    Text("註冊", style: TextStyle(color: MyColor.C66, fontWeight: FontWeight.bold, fontSize: 22)),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 24),
                      child: Text("Email", style: TextStyle(color: MyColor.C66, fontSize: 16)),
                    ),
                    NormalInput(hintText: "請輸入信箱帳號", inputType: NormalInput.Email, controller: emailController),
                    Container(height: 1, color: MyColor.A0),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 24),
                      child: Text("姓名", style: TextStyle(color: MyColor.C66, fontSize: 16)),
                    ),
                    NormalInput(hintText: "請輸入姓名", controller: nameController),
                    Container(height: 1, color: MyColor.A0),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 24),
                      child: Text("電話", style: TextStyle(color: MyColor.C66, fontSize: 16)),
                    ),
                    Row(children: [
                      Container(child: TextBtn("+ $phoneCode ▼", height: 40, width: 80, onTap: choosePhoneCode), color: MyColor.F2),
                      Container(width: 8),
                      Expanded(child: NormalInput(hintText: "請輸入電話", inputType: NormalInput.Phone, controller: phoneController))
                    ]),
                    Container(height: 1, color: MyColor.A0),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 24),
                      child: Text("試讀課程", style: TextStyle(color: MyColor.C66, fontSize: 16)),
                    ),
                    GestureDetector(
                        onTap: chooseLesson,
                        behavior: HitTestBehavior.opaque,
                        child: Row(children: [
                          Expanded(child: Text(lesson == null ? "請選擇試讀課程" : lesson["courseName"], style: TextStyle(color: MyColor.C66))),
                          LocalImage("arrowdown.png", width: 16, height: 44)
                        ])),
                    Container(height: 1, color: MyColor.A0, margin: EdgeInsets.only(bottom: 22)),
                    Row(
                      children: [
                        LocalImage(agree ? "check_on.png" : "check_off.png", width: 20, height: 20, padding: EdgeInsets.all(10), onTap: () {
                          agree = !agree;
                          setState(() {});
                        }),
                        Text("我同意"),
                        TextBtn("隱私權政策", style: TextStyle(color: MyColor.BlueTxt), onTap: () {
                          PageUtil().open(context, WebPage("隱私權連結政策", "https://tw.hitutoracdm.com/service.php#privacy_policy"));
                        }),
                      ],
                    ),
                    Container(height: 22),
                    Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
                      TextBtn("已有帳號", style: TextStyle(color: MyColor.C66, fontWeight: FontWeight.bold, fontSize: 18), onTap: () {
                        PageUtil().back(context);
                      }),
                      TextBtn("註冊", style: TextStyle(color: MyColor.C66, fontWeight: FontWeight.bold, fontSize: 18), onTap: register),
                    ])
                  ]))
            ]))));
  }
}
